import { verifyPwd, saveUserInfo } from 'services/user';
import router from 'umi/router';
import { Toast, Modal } from 'antd-mobile';
import { storage } from 'utils';

const alert = Modal.alert;

let _dispatch;

const userPwd = 'userPwd';

export default {
  namespace: 'login',
  state: {
    user: {},
  },
  subscriptions: {
    setup({ dispatch, history }) {
      _dispatch = dispatch;
      history.listen(location => {
        if (location.pathname === '/login') {
          const userAndPwd = storage.getItem(userPwd);
          // if (userAndPwd) {
          //   dispatch({
          //     type: 'verifyUser',
          //     payload: userAndPwd,
          //   });
          // }
        }
      });
    },
  },
  effects: {
    // 登陆
    *onLogin({ payload }, { call, put }) {
      const { data = {}, user = {} } = payload;
      if (!data.ID) {
        return;
      }
      data.client = 'app';
      // 1. 设置 node端的 用户信息
      const setRes = yield call(saveUserInfo, data);
      // 2. 先设置本地 用户信息
      const { success, msg, subMsg } = setRes.data;
      if (success) {
        // 跳转页面到首页
        yield put({
          type: 'app/setCurrentUser',
          payload: data,
        });

        storage.setItem(userPwd, user);
        // 进入首页
        yield router.push('/');
      } else {
        alert(
          msg,
          subMsg,
          [
            {
              text: '取消',
              onPress: () => console.log('取消登陆'),
              style: 'cancel',
            },
            {
              text: '确定',
              onPress: () => {
                _dispatch &&
                  _dispatch({
                    type: 'onLogin',
                    payload: {
                      data: { ...data, Forced: true },
                      user,
                    },
                  });
              },
            },
          ],
          { cancelable: false }
        );
      }
    },
    // 验证用户信息 如果有用户就登陆
    *verifyUser({ payload }, { call, put }) {
      const res = yield call(verifyPwd, payload);
      const { LoginUser } = res;
      if (LoginUser && LoginUser.ID) {
        yield put({
          type: 'onLogin',
          payload: {
            data: LoginUser,
            user: payload,
          },
        });
      } else {
        return Toast.fail('用户名或密码错误', 1);
      }
    },
    // 退出
    *onLogout(_, { call, put, select }) {
      // 清楚登陆缓存
      storage.removeItem(userPwd);
      const { userInfo } = yield select(_ => _.app);
      const loginUser = {};
      // 设置 node端的 用户信息为空
      // for (const key of Object.keys(userInfo)) {
      //   loginUser[key] = '';
      // }
      loginUser.ID = '';
      yield call(saveUserInfo, { ...loginUser, client: 'app' });
      // 清空本地的用户信息
      yield put({ type: 'app/setCurrentUser', payload: {} });
      yield router.replace('/login');
    },
  },
  reducers: {
    updateState(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};
